import { Body, Controller, Get, HttpException, HttpStatus, Post, Request, Res, UseInterceptors } from '@nestjs/common';
import { QuestionsService } from './questions.service';
import { Questions } from './questions.entity';
import { ValidTokenInterceptor } from '../../interceptor/validToken'
import { ValidRSAInterceptor } from '../../interceptor/validRSA'
import {
  apibefore
} from '../../router'
import { RateLimiterService } from '../rateLimiter/rateLimiter.service';

@Controller(apibefore('/questions'))
@UseInterceptors(ValidTokenInterceptor)
@UseInterceptors(ValidRSAInterceptor)
export class QuestionsController {
  constructor(
    private readonly questionsService: QuestionsService,
    private readonly rateLimiter: RateLimiterService,
  ) {}


  @Post('/create')
  async create(@Body() questionsParam: any, @Request() req) {
    let wx_user = req.headers.wx_user
    let limiter = await this.rateLimiter.consume_question('question_add_' + questionsParam.video_id + '_' + wx_user, 12)
    if(!limiter){
      return new HttpException('操作太频繁，请1分钟后再试', HttpStatus.INTERNAL_SERVER_ERROR)
    }
    //查询是否可以提问
    let isError = await this.questionsService.isCreate(questionsParam.video_id, wx_user, questionsParam.share_uid)
    if(isError?.error){
      return new HttpException(isError.error, HttpStatus.INTERNAL_SERVER_ERROR)
    }

    
    let questions = new Questions()
    questions.wx_user = wx_user
    questions.video_id = questionsParam.video_id
    questions.create_time = new Date()
    let { success, error, type } = await this.questionsService.create(questions, questionsParam.uid, questionsParam.share_uid)
    if(success){
      return type
    }else{
      return new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  @Post('/delete')
  async delete(@Body() data: { video_id: number}, @Request() req) {
    let wx_user = req.headers.wx_user
    let limiter = await this.rateLimiter.consume_question('question_del_' + data.video_id + '_' + wx_user, 25)
    if(!limiter){
      return new HttpException('操作太频繁，请1分钟后再试', HttpStatus.INTERNAL_SERVER_ERROR)
    }
    return this.questionsService.remove(data.video_id, wx_user);
  }

  @Get('/findAll')
  async findAll(){
    return await this.questionsService.findAll()
  }
}
